<?php
include_once('../lib/config.php');
require ($war_root.'/lib/verify.php');
require ($war_root.'/lib/has_char.php');
require ($war_root.'/lib/is_approved.php');
require ($war_root.'/lib/is_admin.php');


$_category = "Admin";
$_title = "";
$admin_active = 1;
$log_char = $character["character_name"];
$debug=0;

if (@$_GET ['a'] != "adding" || @$_GET ['s'] == 2) require ($war_root.'/lib/head.php');

$page = @$_GET ['p'];
$action = @$_GET ['a'];
$raid_id = @$_GET ['raid'];
$system_id = @$system ["system_id"];


/*****************************
 * Start Loot part
 *****************************/

$system_id = $system ["system_id"];
$id = $_GET ['id'];

$sql = "select * from wm_characters where character_system_id = ".$system ["system_id"];
$result = $db->query ( $sql );
while ( $char = $db->fetch_assoc ( $result ) ) {
    $chars [$char ['character_id']] = $char ['character_name'];
 }
asort ( $chars );

$raid_id = $_GET ["raid"];
$sql = "select * from wm_raids  left join wm_instances on wm_instances.instance_id = raid_instance where wm_raids.raid_system_id = $system_id and raid_id = $raid_id";

$result = $db->query ( $sql );
$raid = $db->fetch_assoc ( $result );

if ($_GET ["error"] != "") {
    boxRed ( "Error" );
    echo $_GET ["error"];
    boxBot ();
 }

//
//Fetch all chars for this system and add them to an array for easier fetching and less server load
//


$_category = "Loot";
$_title = "Start";
boxTop ( "$_category: $_title" );

//
// Format the data, and insert it into the database if it checks out
//
if ($_GET ['s'] == 2) {

    $system_id = $_POST ['system_id'];
    $raid_id = $_POST ['raid'];

    $sql = "select * from wm_bosses where boss_instance = " . $raid ["raid_instance"];
    $result = $db->query ( $sql );
    $b = 0;
    while ( $bosses = $db->fetch_assoc ( $result ) ) {
        unset ( $attid, $name_lookup, $bossid, $boid, $sqlboss, $resboss );
        $b ++;
        if ($b > 50) {
            die('Warning, infinte loop occured while adding boss attendees. Please contact an administrator.');
        }
        $bossid = $bosses ['boss_id'];
        $boid = 'boss' . $bossid;
        $raid_id = $_GET['raid'];

        if ($_POST [$boid] == "yes") {
            $attid = 'att-' . $bossid;
            $attdel = $_POST['att_del' . $bossid];
            $credit_id = "creditid".$bossid;
            $credit_id = $_POST[$credit_id];
            $edited = $_POST['edited' . $bossid];
            $rdate = substr ( $raid ['raid_date'], 0, 10 );
            $rdate = explode ( "-", $rdate );
            $hid = 'hour' . $bossid;
            $mid = 'minute' . $bossid;


            $hour = $_POST[$hid];
            $minute = $_POST[$mid];


            if($_POST['unixtime']) $credit_time = $_POST['unixtime'];
            else {
                $date_string = "$rdate[1]/$rdate[2]/$rdate[0] $hour:$minute:00";
                $credit_time = strtotime($date_string);
            }


            //Check names here, to avoid multiple entries corrupting the DB
            $nonames=0;
            if($_POST [$attid] == "") $nonames = 1;
            else $name_lookup = verify_names ( $_POST [$attid], $db, $system_id );

			
            //Check if we're deleting
            $death=0;
            if(is_array($attdel)){
                foreach($attdel as $attn) {
                    //And then delete each record, of present.
                    $sqld = "delete from wm_attendees where attendee_character='$attn' and attendee_credit='$credit_id'";
                    $resultd = $db->query($sqld);
                    if ($resultd != 1) {
                        $death = 1;
                        $sqle = "insert into wm_logs (log_character, log_type, log_description, log_datetime, log_systemid, log_admin) values ('$log_char', 'Raid', Raid $raid_id attendee add/edit FAILED(sql), FROM_UNIXTIME(".time()."), '$system_id', '$admin_active')";
                        $rese = @$db->query($sqle);
                        die ( 'Problems adding attendees, please contact an administrator.' );
                    }
                    else{
                        if($debug > 0) sql_debug($db->error());
                    }
                }
                if($death < 1) echo "All attendees should have been Deleted.";
            }
			
			
            //Insert  boss credit:
            if($edited > 0) $sqlboss = "update wm_credits set credit_boss='$bossid' , credit_date=FROM_UNIXTIME($credit_time), credit_system_id='$system_id' where credit_id='$credit_id'";
            else $sqlboss = "insert into wm_credits (credit_boss, credit_date, credit_raid, credit_system_id) values ('$bossid', FROM_UNIXTIME($credit_time), '$raid_id', '$system_id')";
            $resboss = $db->query ( $sqlboss );
            if ($resboss != 1) {
                $death = 1;
                sql_debug($db->error());
                die ( 'Problems adding boss credit, please contact an administrator. (' . $resboss . ')' );
            }
            else echo 'Credit should have been added<br>';
            unset($ii);
            if($_POST['edited'] > 0 || $credit_id > 0) $ii = $credit_id;
            else $ii = $db->insert_id ( $resboss );




            if($nonames == 1) $foo="bar";
            else {
                //Add the attendance, now that we know all names are clear and credits have been put in
                while ( list ( $name, $cid ) = each ( $name_lookup ) ) { //Will probably turn this into a foreach at some point
                    $sql = "insert into wm_attendees (attendee_character, attendee_credit, attendee_satout, attendee_system_id) values ('$cid', '$ii', '0', '$system_id')";
                    $res = $db->query ( $sql );

                    if ($res != 1) {
                        $death = 1;
                        sql_debug($db->error());
                        die ( 'Problems adding attendees, please contact an administrator.' );
                    }
                    else{
                        if($debug > 0) echo "Attendee $cid should have been added to credit_id: $ii<br>\n";
                    }
                }
                if($death < 1) echo "All attendees should have been added.";
            }
        }

    }
    //if ($death != 1) //header ( "Location: $war_http/administrate.php?p=loot&a=add&raid=$raid_id" );

    //"Your last action(s) were logged for security(and/or debugging) reasons."
    $sql = "insert into wm_logs (log_character, log_type, log_description, log_datetime, log_systemid, log_admin) values ('$log_char', 'Raid', Raid $raid_id Edited, FROM_UNIXTIME(".time()."), $system_id, $system_id, $admin_active)";
    $res = @$db->query($sql);

    if($_POST['edited'] > 0) $whatvar = "Edit";
    else $whatvar = "Add";
    echo "<a href=\"$war_http/admin/loot.php?a=add&raid=$raid_id\">$whatvar loot</a><br>\n";

 }
//
//Form to input raid credit
//
elseif ($_GET ['s'] == 1) {
    $raid_id = $_GET ['raid'];

    echo '<b>Add a Credit</b><br /> to ' . '<a href="'.$war_http.'/raids.php?id=' . $raid ["raid_id"] . '">' . $raid ["instance_name"] . ', ' . date ( "D d M Y", strtotime ( $raid ["raid_date"] ) ) . '</a>' . '<br /><br />';
    echo '<form action="'.$war_http.'/admin/loot.php?raid='.$raid_id.'&s=2" method="post"><input type="hidden" value="'.$system ["system_id"].'" name="system_id"><input type="hidden" value="'.$raid_id.'" name="raid_id"><i>Bosses:</i><br /><br />';

    $sql = "select * from wm_bosses where boss_instance = " . $raid ["raid_instance"];
    $result = $db->query ( $sql );
    while ( $boss = $db->fetch_assoc ( $result ) ) {
        if (! $boss ["boss_trash"]) {
            echo '<b>' . $boss ["boss_name"] . '</b><br \><select name="boss' . $boss ["boss_id"] . '">';
            echo '<option value="no">Alive';
            echo '<option value="yes"> Defeated';
            echo '</select> - ';
            echo time_select ( $boss ["boss_id"] );
            echo '<br \><a href="javascript:unhide(\'hide' . $boss ['boss_id'] . '\');">Attendance</a><br \>';
            echo '<div class="hidden" id="hide' . $boss ['boss_id'] . '"><i>One char name per line, and no empty lines!</i><br \><textarea class="char-att" name="att-' . $boss ['boss_id'] . '">';
            //The option of selecting active chars, instead of typing/copying -n
            //foreach($chars as $char_id => $char_name) echo '<option value="'.$char_id.'">'.$char_name;
            echo '</textarea></div>';
            echo ' <br \>';
        }
    }
    echo "<br /><br />\n";
    echo '<input type="submit" value="Add Attendance"></form>';

}
//
//Edit credit/atendees
//
elseif ($_GET ['s'] == 3) {
    $raid_id = $_GET ['raid'];

    echo '<b>Edit Kills/Attendees:</b><br /> to ' . '<a href="'.$war_http.'/raids.php?a=view&id=' . $raid ["raid_id"] . '">' . $raid ["instance_name"] . ', ' . date ( "D d M Y", strtotime ( $raid ["raid_date"] ) ) . '</a>' . '<br /><br />';
    echo '<form action="'.$war_http.'/admin/loot.php?raid='.$raid_id.'&s=2" method="post"><input type="hidden" value="'.$system ["system_id"].'" name="system_id"><input type="hidden" value="'.$raid_id.'" name="raid_id"><i>Bosses:</i><br /><br />';
    $sql = "select * from wm_credits where credit_raid = " . $raid_id;
    $result = $db->query ( $sql );
    while($creds = $db->fetch_assoc($result)){
        $credit_id[$creds['credit_boss']] = $creds['credit_id'];
        $bosses['kill'][$creds['credit_boss']] = 1;
        $bosses['date'][$creds['credit_boss']] = sqltounix($creds['credit_date']);
        $sqla = "select * from wm_attendees where attendee_credit=".$creds['credit_id'];
        $resulta = $db->query($sqla);
        while($att = $db->fetch_assoc($resulta)){
            $bosses['att'][$creds['credit_boss']][] = $att['attendee_character'];
        }

    }


    $sql = "select * from wm_bosses where boss_instance = " . $raid ["raid_instance"];
    $result = $db->query ( $sql );
    while ( $boss = $db->fetch_assoc ( $result ) ) {
        if (! $boss ["boss_trash"]) {
            $boss_id = $boss["boss_id"];
            $bossdate = $bosses['date'][$boss_id];
            //echo "date: ". $bossdate ." <br>\n";
            echo '<b>' . $boss ["boss_name"] . '</b><br \><select name="boss' . $boss ["boss_id"] . '">';
            echo '<option value="no">Alive';
            if($bosses['kill'][$boss_id] == 1) echo '<option value="yes" selected="selected"> Defeated';
            else echo '<option value="yes"> Defeated';
            echo "</select> - \n";
            echo "<input type=\"hidden\" name=\"unixtime\" value=\"$bossdate\" >\n";
            if($bosses['kill'][$boss_id] == 1) echo "<input type=\"hidden\" name=\"edited".$boss ["boss_id"]."\" value=\"12\" >\n";
            echo '<input type="hidden" name="creditid'.$boss_id.'" value="'.$credit_id[$boss_id].'">'."\n";
            echo time_select ($boss_id, $bossdate);
            if(is_array($bosses['att'][$boss_id])){
                echo '<br>Check to delete<br><i>Will delete items looted by this person as well</i><br>';
                foreach($bosses['att'][$boss_id] as $atte){
                    echo '<input type="checkbox" name="att_del'.$boss ["boss_id"].'[]" value="'.$atte.'">'.$chars[$atte]."<br>\n";
                }
            }
            echo '<br><a href="javascript:unhide(\'hide' . $boss ['boss_id'] . '\');">Attendance</a><br \>';
            echo '<div class="hidden" id="hide' . $boss ['boss_id'] . '"><i>One char name per line, and no empty lines!</i><br \><textarea class="char-att" name="att-' . $boss ['boss_id'] . '">';
            echo '</textarea></div>';
            echo ' <br>';
        }
    }
    echo "<br /><br />\n";
    echo '<input type="submit" value="Add Attendance"></form>';

}

//
//Select boss to add/edit loot or actual deleting/inserting into the database.
//
elseif ($_GET ['a'] == "add") {
    $raid_id = $_GET ['raid'];
    $credit_id = @$_GET['cid'];
    $boss_id = @$_GET['boid'];

    $sql = "select * from wm_bosses where boss_instance = " . $raid ["instance_id"];
    $result = $db->query($sql);
    while($bosses = $db->fetch_assoc($result)) {
        $bosse[$bosses['boss_id']] = $bosses['boss_name'];
        $trash[$bosses['boss_id']] = $bosses['boss_trash'];
    }

    echo '<form action="'.$war_http.'/admin/loot.php" method="get">';
    echo '<input type="hidden" name="a" value="add">';
    echo '<input type="hidden" name="raid" value="'.$raid ["raid_id"].'">';
    echo '<select name="boid">';

    $sql = "select * from wm_credits where credit_raid = ".$raid_id;
    $result = $db->query($sql);
    while ($boss = $db->fetch_assoc($result)) {
        unset($select);
        if($boss_id == $boss['credit_boss']){
            $select = 'selected="selected"';
            $credit_id = $boss['credit_id'];
        }
        echo '<option value="'.$boss['credit_boss'].'" '.$select.'>'.$bosse[$boss['credit_boss']]."<br>\n";
    }
    echo '<input type="submit" value="Go to">';
    echo "</select>\n";
    echo ' or <a href="'.$war_http.'/admin/loot.php?s=3&raid='.$raid_id.'">add another boss defeat.</a>';
    echo "</form>\n\n";

    //Second step of adding loot
    //It's here that we delete or insert things into the db, after checking that it's okey data.
    if(isset($_GET['boid']) && $_GET['cid']){
        $ap = $_GET['ap'];


        if($ap=="d"){
            if(!is_numeric($_GET['raid']) || !is_numeric($_GET['boid']) || !is_numeric($_GET['cid']) || !is_numeric($_GET['di'])|| !is_numeric($_GET['dc'])){
                die('Corrupt data, either try again, or contact an administrator if the problem persists.');
            }

            $loot_credit = $_GET["cid"];
            $system_id = $system["system_id"];
            $loot_item = $_GET["di"];
            $loot_character = $_GET["dc"];


            $sqlg = "delete from wm_loots where loot_character='$loot_character' and loot_item='$loot_item' and loot_credit='$loot_credit'";
            $resultg = $db->query($sqlg);
            if ($resultg == false) {
                $death = 1;
                sql_debug($db->error());
                die ( 'Problems deleting item, please contact an administrator.' );
            }
            else{
                if($debug > 0) echo "Loot $loot_item to ".$chars[$loot['loot_character']]." from $loot_credit . SUCCESS<br>\n";
            }
            if($death < 1) echo "All attendees should have been added.<br>\n";

            reprocessDKP($db, $system["system_id"], $_GET['debug']);
            echo "DKP has be reprocessed.<br>\n";
        }
        elseif($ap=="a"){
            // Raut - add inserts
            if (!is_numeric($_GET['raid']) || !is_numeric($_GET['boid']) || !is_numeric($_GET['cid'])) {
                die('Corrupt data, either try again, or contact an administrator if the problem persists.');
            }
            $loot_credit = $_GET["cid"];
            $system_id = $system["system_id"];
            
            // Handle bids from the fancy loot module
            for ($i=0; $i<10; $i++) {
                $i_item = 'item_id_'.$i;
                if (isset($_GET[$i_item]) && $_GET[$i_item] != '--') {
                    $i_buyer = "format_".$i."_".$_GET[$i_item];
                    if (isset($_GET[$i_buyer])) {
                        if (!is_numeric($_GET[$i_item]) || !is_numeric($_GET[$i_buyer])) {
                            die('Corrupt data, item and/or buyer attributes not integers');
                        }
                        $sql = "SELECT wish_level FROM wm_wishes
                                WHERE wish_character='".$_GET[$i_buyer]."' AND
                                      wish_item='".$_GET[$i_item]."' AND
                                      wish_system_id='$system_id'";
                        $result = $db->query($sql);
                        $wish_level = $db->fetch_row($result);
                        if (!is_array($wish_level) && !is_numeric($wish_level[0])) {
                            die('Corrupt data, no wish found for character with a wish');
                        }
                        $sql = "INSERT INTO wm_loots (loot_character, loot_item, loot_level, loot_system_id, loot_credit) 
                                   VALUES ('".$_GET[$i_buyer]."', '".$_GET[$i_item]."', '".$wish_level[0]."', '$system_id', '$loot_credit')";
                        $result = $db->query($sql);
                        // Show a nice item registered block
                        $item['item_id'] = $_GET[$i_item];
                        echo '<br/>Registered <a href="character.php?id='.$_GET[$i_buyer].'">'.$chars[$_GET[$i_buyer]]."</a> (auto-loot): <br>";
                        show_link($item);
                        echo "for <b>".bid2text($wish_level[0])."</b> bid.<br/>";
                    }
                    // Handle cleaning up wishlists
                    $i_delete = "delete_".$i."_".$_GET[$i_item];
                    if (isset($_GET[$i_buyer]) && isset($_GET[$i_delete])) {
                        $sql = "DELETE FROM wm_wishes 
                                WHERE wish_character='".$_GET[$i_buyer]."' AND
                                      wish_item='".$_GET[$i_item]."' AND
                                      wish_system_id='$system_id'";
                        $result = $db->query($sql);
                        echo "<b>Deleted wish.</b><br/>";
                    }
                    //echo "<br/>";
                }
            }
            // Handle manually inserted loot
            for ($i=0; $i<10; $i++) {
                $i_buyer = 'looter_id_'.$i;
                if (isset($_GET[$i_buyer]) && $_GET[$i_buyer] != '--') {
                    $i_item = "manual_item_id_".$i;
                    $i_lvl = "lvl_".$i;
                    if (isset($_GET[$i_item]) && $_GET[$i_item] != '--') {
                        // Strictly sanity, values should be present at all times and integers
                        if (!isset($_GET[$i_lvl]) || !is_numeric($_GET[$i_item]) || !is_numeric($_GET[$i_lvl])) {
                            die('Corrupt data, either try again, or contact an administrator if the problem persists.');
                        }
                        $sql = "INSERT INTO wm_loots (loot_character, loot_item, loot_level, loot_system_id, loot_credit) 
                                VALUES ('".$_GET[$i_buyer]."', '".$_GET[$i_item]."', '".$_GET[$i_lvl]."', '$system_id', '$loot_credit')";
                        $result = $db->query($sql);
                        // Show a nice item registered block
                        $item['item_id'] = $_GET[$i_item];
                        echo '<br/>Registered <a href="character.php?id='.$_GET[$i_buyer].'">'.$chars[$_GET[$i_buyer]]."</a> (manual-loot): <br>";
                        show_link($item);
                        echo "for <b>".bid2text($_GET[$i_lvl])."</b> bid.<br/>";
                    }
                }
            }
            reprocessDKP($db, $system["system_id"], $_GET['debug']);
            echo "<br/>DKP reprocessed!";
        }
        else die("An error occured, please contact an administator");
    }
    elseif(isset($boss_id)){        
        $sql = "select * from wm_loots where loot_credit = ".$credit_id;
        $result = $db->query($sql);
        echo "<br>\n<p><b>Already looted:</b></p>\n <br>\n";
        while ($loot = $db->fetch_assoc($result)) {
            $f = $loot['loot_level'];
            $bid = bid2text($f);
            
            $ting['item_id'] = $loot['loot_item'];
            echo '<a href="character.php?id='.$loot['loot_character'].'">'.$chars[$loot['loot_character']]."</a> looted: <br>";
            show_link($ting);
            echo "for <b>".$bid."</b>(".number_format($loot['loot_bid'], 2).") bid.";

            echo '<form method="get" action="'.$war_http.'/admin/loot.php">';
            echo '<input type="hidden" name="di" value="'.$loot['loot_item'].'">';
            echo '<input type="hidden" name="dc" value="'.$loot['loot_character'].'">';
            echo '<input type="hidden" name="a" value="add">';
            echo '<input type="hidden" name="raid" value="'.$raid ["raid_id"].'">';
            echo '<input type="hidden" name="boid" value="'.$boss_id.'">';
            echo '<input type="hidden" name="cid" value="'.$credit_id.'">';
            echo '<input type="hidden" name="ap" value="d">';
            echo '<input class="item_delete" type="submit" value="Delete">';
            echo "</form><br> <br>\n";

        }

        echo "<br><p><b>Add additional loot:</b></p><br>\n";
        echo '<form action="'.$war_http.'/admin/loot.php" method="get">';
        echo '<input type="hidden" name="a" value="add">';
        echo '<input type="hidden" name="raid" value="'.$raid ["raid_id"].'">';
        echo '<input type="hidden" name="boid" value="'.$boss_id.'">';
        echo '<input type="hidden" name="cid" value="'.$credit_id.'">';
        echo '<input type="hidden" name="ap" value="a">';
        echo "\n";
        // Begin conversion - Raut
        
        // List items
        // Add trash loot to all bosses, since we don't have a trash "boss" to select
        $ids = $boss_id;
        foreach($trash as $b => $t) if ($t == 1)  $ids .= ",$b";
        $sql = "select * from wm_items where item_boss in (".$ids.")";
	echo '<!-- boss IDs: '.$ids.' -->';
        $result = $db->query($sql);
        $i=0;
	echo '<!-- items from loot table: ';
        while ($items = $db->fetch_assoc($result)) {
            $i++;
            if($i==1) $ifetch = $items['item_id'];
            else $ifetch .= ",".$items['item_id'];
	    echo $items['item_id'].', ';
        }
	echo '-->';

        $sql = "select * from item_cache where item_id in ($ifetch) order by item_name";
        $result = $db->query($sql);
                
        while ($it = $db->fetch_assoc($result)) {
            $items[$it['item_id']] = $it['item_name']; 
        }
        
	echo '<!-- ';
	foreach ($items as $item_id => $item_name) { echo 'id: '.$item_id.', name: '.$item_name.' '; }
	echo '-->';

        // Get attendees
        $sql = "select * from wm_attendees where attendee_credit = ".$credit_id;
        $result = $db->query($sql);
        $attn = array();
        while ($attd = $db->fetch_assoc($result)) {
            $attn[$attd['attendee_character']] = $chars[$attd['attendee_character']];
        }
        natcasesort($attn);
        // Create lists of loot and bids
        $bids = array();
        foreach ($items as $item_id => $item_name) {
            $sql = "select *, wm_characters.* 
                    from wm_wishes, wm_characters 
                    where wish_item = $item_id and  
                          wish_system_id = $system_id and 
                          wm_wishes.wish_character = wm_characters.character_id and 
                          wm_characters.character_hidden = 0 
                    order by wish_level desc";
            $result = $db->query($sql);

            $bids[$item_id] = array();
            $rows[$item_id] = array(); 
            $bids[$item_id]['bids'] = array();
            $bids[$item_id]['offspec'] = array();
            
            while($ite = $db->fetch_assoc($result)) {
                $bid = $ite["character_dkp"] * bid2perc($ite["wish_level"]);
                if($bid < ($floor_max)) {
                    $bid = $floor_max;
                }
                if($ite["wish_level"] == 1) {
                    $bids[$item_id]['offspec'][$ite["character_id"]] = $ite["character_dkp"];
                    $row[$item_id][$ite["character_id"]] = $ite;
                } else {
                    $bids[$item_id]['bids'][$ite["character_id"]] = $bid;
                    $row[$item_id][$ite["character_id"]] = $ite;
                }
            }
            arsort($bids[$item_id]['bids']);
            arsort($bids[$item_id]['offspec']);
        }
    
        $LOOT_SLOTS = 10;
        $iter = 0;
        echo '<fieldset style="width: 510px;float:left">';
        while ($iter < $LOOT_SLOTS) {
            echo '<select name="item_id.'.$iter.'" onchange="hideAll(\'list_'.$iter.'\'); unhideSelectedItem(this, \''.$iter.'.\');">';
            echo '<option value="--">Select item</option>';
            foreach ($items as $item_id => $item_name)
                echo '<option value="'.$item_id.'">'.$item_name."</option>";
            echo '</select>';
            echo "\n";
                        
            echo '<div style="width: 500px;" id="list_'.$iter.'">';
            foreach ($items as $item_id => $item_name) {
                echo "<div class=\"hidden\" id=\"$iter.$item_id\"><br/>\n";
                reset($bids[$item_id]['bids']);
		$tmp_i = array();
		$tmp_i['item_id'] = $item_id;
		show_link($tmp_i);
                echo '<fieldset class="options">';
                echo "Regular bids:<br/>\n";
                echo "\n";
                echo '<fieldset>';
                while(list($n, $ite) = each($bids[$item_id]['bids'])) {
                    $ite = $row[$item_id][$n];
                    if (!array_key_exists($ite["character_id"], $attn)) continue;
                    echo '<input type="radio" name="format_'.$iter.'_'.$item_id.'" value="'.$ite["character_id"].'" id="radio_player'.$iter.'"/>';
                    echo '<b>'.number_format($bids[$item_id]['bids'][$ite["character_id"]], 2).'</b> dkp ';
                    echo bid2text($ite["wish_level"]).' by ';
                    echo cclass($ite["character_class"]);
                    echo ' <a href="character.php?id='.$ite["wish_character"].'">'.$ite["character_name"].'</a> (';
                    echo number_format($ite["character_dkp"], 2).' dkp)<br />';
                    echo "\n";
                }
                echo '</fieldset>';
                reset($bids[$item_id]['offspec']);
                echo "Offspec bids:<br/>\n";
                echo "\n";
                echo '<fieldset>';
                while(list($n, $ite) = each($bids[$item_id]['offspec'])) {
                    $ite = $row[$item_id][$n];
                    if (!array_key_exists($ite["character_id"], $attn)) continue;
                    echo '<input type="radio" name="format_'.$iter.'_'.$item_id.'" value="'.$ite["character_id"].'" id="radio_player'.$iter.'"/>';
                    echo '<b>'.number_format($bids[$item_id]['offspec'][$ite["character_id"]], 2).'</b> dkp ';
                    echo bid2text($ite["wish_level"]).' by ';
                    echo cclass($ite["character_class"]);
                    echo ' <a href="character.php?id='.$ite["wish_character"].'">'.$ite["character_name"].'</a><br />';
                    echo "\n";
                }
                
                echo '</fieldset>';
                echo '<br/><input type="checkbox" name="delete_'.$iter.'_'.$item_id.'" id="cb_'.$iter.'"  checked="checked"/>';
                echo 'Delete from wishlist?';

                echo "</fieldset>\n";
                echo "</div>";
            }
            $iter++;
            echo "</div>\n";
        }
        echo '</fieldset>';

        // Begin manual block

        echo '<fieldset style="width: 450px;float:left">';
        $iter = 0;
        while ($iter < $LOOT_SLOTS) {
            reset($attn);
	    asort($attn);
            echo '<select name="looter_id_'.$iter.'">';
            echo '<option value="--">--'."</option>\n";
            foreach ($attn as $key => $val) {
                echo '<option value="'.$key.'">'.$val."</option>\n";
            }
            echo '</select>';
            
            echo '<select name="manual_item_id_'.$iter.'">';
            echo '<option value="--">--'."</option>\n";
            foreach ($items as $item_id => $item_name) {
                echo '<option value="'.$item_id.'">'.$item_name."";
            }
            echo '</select>';
            echo '<select name="lvl_'.$iter.'">';
            for ($i=bid_max(); $i > 0; $i--) {
                echo '<option value='.$i.'>'.bid2text($i).'</option>';
            }
            echo '</select><br />';
            $iter++;
        }
        echo '</fieldset>';
        echo '<div style="clear:both"></div>'; 
        echo '<input type="submit" value="Add Loot"></form>';
    }
}
//
//Main page to show, when nothing is selected
//
 else {
     $system_id = $system ["system_id"];
     if(isset($_GET['nr'])) $n_raids = $_GET['nr'];
     else $n_raids = 1;


     echo 'Add/Edit boss kills/attendees/loot:<br /><br />' . '<table>' . '<tr>' . '<th width="50">Modify</th>' . '<th>Where</th>' . '<th>When</th>' . '<th>Bosses</th>' . '<th width="40">ID</th>' . '</tr>';

     $per_page = 20;
     $offset = ($n_raids -1) * $per_page;
     $sql = "select *, wm_instances.instance_name
                        from wm_raids left join wm_instances on wm_raids.raid_instance = wm_instances.instance_id
                        where wm_raids.raid_system_id = $system_id order by raid_date desc limit $offset, $per_page";
     $result = $db->query ( $sql );

     $i = 0;

     while ( $raid = $db->fetch_assoc ( $result ) ) {
         $i ++;
         $sqlb = "select *, wm_bosses.* from wm_credits left join wm_bosses on wm_bosses.boss_id = credit_boss where credit_raid = '" . $raid ["raid_id"] . "' and credit_system_id = $system_id order by credit_date asc";
         $resb = $db->query ( $sqlb );
         $ib = 0;
         while ( $cred = $db->fetch_assoc ( $resb ) ) {
             $ib ++;
             $bosses [] = $cred ['boss_name'] . '| <i>(' . date ( "H:i", strtotime ( $cred ["credit_date"] ) ) . ')</i><br />';
         }

         echo '<tr>';
         echo '<td align="center">';
         echo '<a href="'.$war_http.'/raids.php?a=view&id=' . $raid ["raid_id"] . '"><img src="' . $war_http . '/images/list.gif" alt="View"></a> ';
         echo '<a href="'.$war_http.'/admin/loot.php?a=add&raid='.$raid ["raid_id"].'"><img src="'.$war_http.'/images/edit2.gif" alt="Edit"></a><br>';
         echo '</td>';
         echo '<td>' . $raid ["instance_name"] . '</td>';
         echo '<td>' . date ( "D d M Y", strtotime ( $raid ["raid_date"] ) ) . '</td>';
         echo '<td>Defeated: ' . $ib;
         echo ' <a href="javascript:unhide(\'hide' . $i . '\');">Show/hide</a><br \><div id="hide' . $i . '"  class="hidden">';
         if ($bosses != true) {
             echo "No bosses killed.";
         }
         else {
             foreach ( $bosses as $bos ) {
                 list ( $boss, $time ) = explode ( '|', $bos );
                 echo $boss . $time;
             }
         }
         echo '</div></td>';
         echo '<td>T' . $system ["system_tier"] . 'R' . $raid ["raid_id"] . '</td>';
         echo '</tr>';
         unset ( $bosses );
     }
     echo '</table>';

     $query = "SELECT * FROM wm_raids WHERE raid_system_id = $system_id";
     $result = $db->query($query);
     $numr = $db->num_rows($result);

     $maxPage = ceil($numr/$per_page);

     $self = $_SERVER['PHP_SELF'];
     $nav  = '';

     for($page = 1; $page <= $maxPage; $page++) {
         if ($page == $n_raids) $nav .= " $page ";
         else $nav .= " <a href=\"$self?p=loot&nr=$page\">$page</a> ";
     }



     if ($n_raids > 1){
         $page  = $n_raids - 1;
         $prev  = " <a href=\"$self?p=loot&nr=$page\">[Prev]</a> ";
     }
     else $prev  = ' ';

     if ($n_raids < $maxPage){
         $page = $n_raids + 1;
         $next = " <a href=\"$self?p=loot&nr=$page\">[Next]</a> ";
     }
     else $next = ' ';
     echo "<div align=center>$prev $nav $next</div>";

 }

boxBot ();

require ($war_root.'/lib/foot.php');

?>
